"""
服务初始化器，用于初始化和注册所有服务
"""
from typing import Dict, Type, Any

from app.services.service_locator import ServiceLocator
from app.services.config_service import IConfigService
from app.services.websocket_service import IWebSocketService
from app.services.comment_service import ICommentService
from app.services.ai_service import IAIService
from app.services.speech_service import ISpeechService
from app.services.script_service import IScriptService
from app.services.audio_service import IAudioService
from app.services.sync_service import ISyncService
from app.controllers.websocket_controller import WebSocketController
from app.state.app_state_manager import AppStateManager

# 导入服务实现
from app.services.config_service_impl import ConfigService
from app.services.websocket_service_impl import WebSocketService
from app.services.comment_service_impl import CommentService
from app.services.ai_service_impl import AIService
from app.services.speech_service_impl import SpeechService
from app.services.script_service_impl import ScriptService
from app.services.audio_service_impl import AudioService
from app.services.sync_service_impl import SyncService
from app.services.message_processor import MessageProcessor


def initialize_services(
    config_service_cls: Type[IConfigService],
    websocket_service_cls: Type[IWebSocketService],
    comment_service_cls: Type[ICommentService],
    ai_service_cls: Type[IAIService],
    speech_service_cls: Type[ISpeechService],
    script_service_cls: Type[IScriptService],
    audio_service_cls: Type[IAudioService],
    sync_service_cls: Type[ISyncService],
) -> None:
    """
    初始化并注册所有服务
    
    @param config_service_cls: 配置服务类
    @param websocket_service_cls: WebSocket 服务类
    @param comment_service_cls: 评论服务类
    @param ai_service_cls: AI 服务类
    @param speech_service_cls: 语音服务类
    @param script_service_cls: 脚本服务类
    @param audio_service_cls: 音频服务类
    @param sync_service_cls: 音画同步服务类
    """
    # 清除现有服务
    ServiceLocator.clear()
    
    # 初始化状态管理器（先于其他服务）
    ServiceLocator.initialize()
    
    # 初始化配置服务
    config_service = config_service_cls()
    ServiceLocator.register(IConfigService, config_service)
    config_service.load_config()
    
    # 初始化 WebSocket 服务
    websocket_service = websocket_service_cls()
    ServiceLocator.register(IWebSocketService, websocket_service)
    
    # 初始化评论服务
    comment_service = comment_service_cls()
    ServiceLocator.register(ICommentService, comment_service)
    
    # 初始化 AI 服务
    ai_service = ai_service_cls()
    ServiceLocator.register(IAIService, ai_service)
    
    # 初始化语音服务
    speech_service = speech_service_cls()
    ServiceLocator.register(ISpeechService, speech_service)
    
    # 初始化脚本服务
    script_service = script_service_cls()
    ServiceLocator.register(IScriptService, script_service)
    
    # 初始化音频服务
    audio_service = audio_service_cls()
    ServiceLocator.register(IAudioService, audio_service)
    
    # 初始化音画同步服务
    sync_service = sync_service_cls()
    ServiceLocator.register(ISyncService, sync_service)
    
    # 设置服务之间的依赖关系
    # WebSocket 服务 -> 评论服务
    if hasattr(websocket_service, 'set_comment_service'):
        websocket_service.set_comment_service(comment_service)
    
    # 评论服务 -> AI 服务
    if hasattr(comment_service, 'set_ai_service'):
        comment_service.set_ai_service(ai_service)
    
    # 脚本服务 -> 语音服务
    if hasattr(script_service, 'set_speech_service'):
        script_service.set_speech_service(speech_service)
    
    # AI服务 -> 语音服务
    if hasattr(ai_service, 'set_speech_service'):
        ai_service.set_speech_service(speech_service)
    
    # 配置服务到各个服务的配置
    _configure_services(config_service)
    
    # 设置事件监听器
    _setup_event_listeners()
    
    # 初始化并注册控制器
    _initialize_controllers()
    
    # 初始化消息处理器（在所有服务初始化之后）
    _initialize_message_processor()

def _configure_services(config_service: IConfigService) -> None:
    """
    配置所有服务
    
    @param config_service: 配置服务
    """
    try:
        # 获取所有配置
        config = config_service.get_all_config()
        
        # 配置 WebSocket 服务
        websocket_service = ServiceLocator.get(IWebSocketService)
        if websocket_service and "websocket" in config:
            websocket_service.configure(config["websocket"])
        
        # 配置 AI 服务
        ai_service = ServiceLocator.get(IAIService)
        if ai_service and "ai" in config:
            ai_service.configure(config["ai"])
        
        # 配置语音服务
        speech_service = ServiceLocator.get(ISpeechService)
        if speech_service and "speech" in config:
            speech_service.configure(config["speech"])
        
        # 配置脚本服务
        script_service = ServiceLocator.get(IScriptService)
        if script_service and "script" in config:
            script_service.configure(config["script"])
        
        # 配置音频服务
        audio_service = ServiceLocator.get(IAudioService)
        if audio_service and "audio" in config:
            audio_service.configure(config["audio"])
        
        # 配置音画同步服务
        sync_service = ServiceLocator.get(ISyncService)
        if sync_service and "sync" in config:
            sync_service.configure(config["sync"])
        
    except Exception as e:
        print(f"配置服务失败: {str(e)}")

def _setup_event_listeners() -> None:
    """
    设置事件监听器
    """
    # 获取各服务
    websocket_service = ServiceLocator.get(IWebSocketService)
    comment_service = ServiceLocator.get(ICommentService)
    ai_service = ServiceLocator.get(IAIService)
    speech_service = ServiceLocator.get(ISpeechService)
    script_service = ServiceLocator.get(IScriptService)
    audio_service = ServiceLocator.get(IAudioService)
    
    # 添加事件监听器
    if websocket_service and comment_service:
        # WebSocket 服务 -> 评论服务
        websocket_service.add_listener("message_received", 
                                      lambda event: _on_websocket_message(event, comment_service))
    
    if ai_service and comment_service:
        # AI 服务 -> 评论服务
        ai_service.add_listener("comment_analyzed", 
                               lambda event: _on_ai_analysis_completed(event, comment_service))

def _on_websocket_message(event, comment_service):
    """
    处理 WebSocket 消息事件
    
    @param event: 事件对象
    @param comment_service: 评论服务
    """
    try:
        message = event.data
        # 调用评论服务处理消息
        if hasattr(comment_service, 'process_message'):
            comment_service.process_message(message)
    except Exception as e:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"处理 WebSocket 消息事件失败: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
    
def _on_ai_analysis_completed(event, comment_service):
    """
    处理 AI 分析完成事件
    
    @param event: 事件对象
    @param comment_service: 评论服务
    """
    try:
        result = event.data
        # 处理分析结果
        # 这里可以添加处理逻辑，例如更新评论的分析结果
        import logging
        logger = logging.getLogger(__name__)
        logger.info(f"AI 分析完成: {result}")
    except Exception as e:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"处理 AI 分析完成事件失败: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())

def _initialize_controllers() -> None:
    """
    初始化并注册控制器
    """
    # 初始化WebSocket控制器
    websocket_controller = WebSocketController()
    ServiceLocator.register(WebSocketController, websocket_controller)

def _initialize_message_processor() -> None:
    """
    初始化消息处理器
    """
    try:
        # 获取消息处理器实例
        processor = MessageProcessor.get_instance()
        
        # 获取日志记录器
        from app.utils.logger import Logger
        logger = Logger.get_logger("service_initializer")
        
        # 获取评论服务
        comment_service = ServiceLocator.get(ICommentService)
        
        # 添加监听器，将消息处理器的消息转发给评论服务
        if comment_service:
            # 定义消息转发函数
            def forward_to_comment_service(message):
                try:
                    # 记录转发信息
                    message_type = message.get('type', 'unknown')
                    message_id = message.get('message_id', 'unknown')
                    logger.info(f"将消息转发给评论服务: 类型={message_type}, ID={message_id}")
                    
                    # 将消息转发给评论服务
                    comment_service.process_message(message)
                except Exception as e:
                    logger.error(f"转发消息到评论服务失败: {str(e)}")
                    import traceback
                    logger.error(f"异常堆栈: {traceback.format_exc()}")
            
            # 注册消息转发监听器
            processor.add_listener(forward_to_comment_service)
            logger.info("已添加消息处理器到评论服务的转发监听器")
        else:
            logger.warning("评论服务不可用，无法添加消息处理器监听器")
        
        # 记录初始化信息
        logger.info("消息处理器初始化完成")
        
    except Exception as e:
        from app.utils.logger import Logger
        logger = Logger.get_logger("service_initializer")
        logger.error(f"初始化消息处理器失败: {str(e)}")
        import traceback
        logger.error(f"异常堆栈: {traceback.format_exc()}") 